package xxhui.space.newsclient.Adapter;

import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import xxhui.space.newsclient.Bean.HeadlineItem;
import xxhui.space.newsclient.R;

/**
 * Created by hui on 2017/7/2.
 */
//头条item，点击用户界面的列表
public class UserDetatlRecyclerViewAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder>  {
    private List<HeadlineItem> data;//textview的显示的字符串数据
    private OnItemClickListener clickListener;//给RecyclerView添加点击事件

    public UserDetatlRecyclerViewAdapter(List<HeadlineItem> data) {
        this.data = data;
    }//初始化时注入数据

    public void setOnItemClickListener(OnItemClickListener itemClickListener){//设置注入item点击监听
        clickListener = itemClickListener;
    }

    /**
     * 解析布局，并注入到viewHolder
     * @return 给下一步提供一个ViewHolder
     */
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.user_detail_item,parent,false);
        return new ViewHolder(v);
    }

    /**
     * 给ViewHolder里面的控件绑定数据
     * @param holder
     * @param position
     */
    //犹豫给定图片没有数据格式，默认设置为ic_launcher
    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
        if(data!=null&&data.size()>=position){
            HeadlineItem item = data.get(position);
            ViewHolder itemHolder = ((ViewHolder)holder);
            if(item.getPreviewPicUri()!=""){
                itemHolder.articlePic.setImageResource(R.mipmap.ic_launcher);
            }
            itemHolder.title.setText(item.getTitle());
            itemHolder.content.setText(item.getContentPart());
        }

    }

    @Override
    public int getItemCount() {
        return data.size();
    }

    /**
     * 内部类ViewHolder，用于保存绑定控件，如果设置了点击事件，给控件设置点击监听
     */
    class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{

        @BindView(R.id.item_article_pic) ImageView articlePic;
        @BindView(R.id.item_title) TextView title;
        @BindView(R.id.item_content) TextView content;

        public ViewHolder(View itemView) {
            super(itemView);
            ButterKnife.bind(this, itemView);
        }

        @Override
        public void onClick(View v) {
            if(clickListener!=null){
                clickListener.onItemClick(v,getPosition());
            }
        }
    }

    /**
     * 定义一个接口用于外部实现RecycleView的item的操作
     */
    public interface OnItemClickListener {
        void onItemClick(View v, int position);
    }

}